package com.appspot.widget.mail;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appspot.widget.base.BaseServlet;

public class MailServiceImpl extends BaseServlet {

	private static final long serialVersionUID = -5347378827779236545L;

	private String sendMail(String[] from, ArrayList<String[]> toList,
			ArrayList<String[]> ccList, ArrayList<String[]> bccList,
			String subject, String body, String htmlSpp) {

		StringBuilder sb = new StringBuilder();

		if (from == null) {
			sb.append("Error: Please input from information!");
			return sb.toString();
		}
		if (subject == null) {
			sb.append("Error: Please input subject information!");
			return sb.toString();
		}
		if (body == null) {
			sb.append("Error: Please input body information!");
			return sb.toString();
		}
		if (toList == null && ccList == null && bccList == null) {
			sb.append("Error: Please input at least one recipeint!");
			return sb.toString();
		}

		if (toList.size() == 0 && ccList.size() == 0 && bccList.size() == 0) {
			sb.append("Error: Please input at least one recipeint!");
			return sb.toString();
		}

		Properties props = new Properties();
		Session session = Session.getDefaultInstance(props, null);

		try {
			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(from[0], from[1]));

			// TO
			if (toList != null) {
				for (String[] to : toList) {
					msg.addRecipient(Message.RecipientType.TO,
							new InternetAddress(to[0], to[1]));
				}
			}
			// CC
			if (ccList != null) {
				for (String[] to : ccList) {
					msg.addRecipient(Message.RecipientType.CC,
							new InternetAddress(to[0], to[1]));
				}
			}
			// BCC
			if (bccList != null) {
				for (String[] to : bccList) {
					msg.addRecipient(Message.RecipientType.BCC,
							new InternetAddress(to[0], to[1]));
				}
			}

			subject = URLDecoder.decode(subject, "UTF-8");
			subject = MimeUtility.encodeText(subject, "UTF-8", "B");
			msg.setSubject(subject);
			if (htmlSpp.equals("0"))
				msg.setText(body);
			else {
				Multipart mp = new MimeMultipart();
				MimeBodyPart htmlPart = new MimeBodyPart();
				htmlPart.setContent(body, "text/html");
				mp.addBodyPart(htmlPart);
				msg.setContent(mp);
			}

			Transport.send(msg);
			sb.append("Success: " + new Date());

		} catch (Exception e) {
			sb.append("Error: " + e.getMessage() + "<br/>");
		}

		return sb.toString();

	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String subject = req.getParameter("subject");
		if (subject == null) {
			resp.setStatus(626);
			resp.getWriter().write("Please input a subject for the mail.");
			return;
		}
		String body = req.getParameter("body");
		if (body == null) {
			resp.setStatus(626);
			resp.getWriter().write("Please input a body for the mail.");
			return;
		}
		String htmlSpp = req.getParameter("htmlSpp");
		if (htmlSpp == null)
			htmlSpp = "0";

		String[] from = { "unity.mbcla@gmail.com", "Unity MBCLA" };
		// String[] from = { "wannadream@gmail.com", "Duke Wang" };
		ArrayList<String[]> toList = new ArrayList<String[]>();
		toList.add(new String[] { "wannadream@gmail.com", "Duke Wang" });
		resp.getWriter().write(
				sendMail(from, toList, null, null, subject, body, htmlSpp));
	}
}
